//
//  TYNetWorkTool.m
//  XXOO
//
//  Created by wbb on 2019/4/10.
//  Copyright © 2019 wbb. All rights reserved.
//

#import "TYNetWorkTool.h"
#import "WDUtil.h"
#import <AFNetworking/AFNetworking.h>

@interface AFNetworkClient : AFHTTPSessionManager
//@property (nonatomic, assign) BOOL isURL;
//@property (nonatomic, copy) NSString * urlString;
+ (instancetype)sharedClient;

@end
@implementation AFNetworkClient

+ (instancetype)sharedClient
{
    static AFNetworkClient *_sharedClient = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        _sharedClient = [AFNetworkClient manager];
        // 设置请求接口回来的时候支持什么类型的数据
        _sharedClient.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*", nil];//[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"application/x-json",@"text/html",nil];
        
//        [_sharedClient.requestSerializer setValue:@"5" forHTTPHeaderField:@"Client-Type"];
        _sharedClient.responseSerializer = [AFJSONResponseSerializer serializer];
        _sharedClient.requestSerializer = [AFJSONRequestSerializer serializer];

        
        
    });
    
    return _sharedClient;
}

@end

@implementation TYNetWorkTool

/**
 *  post请求
 *
 *  @param url          链接
 *  @param parameters   参数
 *  @param successBlock 成功block
 *  @param failureBlock 失败block
 */
+(void)postRequest:(NSString*)url parameters:(NSDictionary *)parameters successBlock:(void (^)(BOOL success,id data,NSString* msg))successBlock failureBlock:(void (^)(NSString* description))failureBlock{
    
    NSString *URLStr = [NSString stringWithFormat:@"%@%@",URL_main,url];
    NSMutableDictionary *mutableParams = [NSMutableDictionary dictionaryWithDictionary:[NSDictionary nullDic:parameters?:@{}]];
    NSString *token = [USER_DEFAULTS objectForKey:@"token"];
    NSLog(@"token=== %@",[NSString stringWithFormat:@"Bearer %@",[WDUtil getInfoForKey:TY_TOKEN]] );
    NSMutableDictionary *headers = @{}.mutableCopy;
    headers[@"Authorization"] = [NSString stringWithFormat:@"Bearer %@",[WDUtil getInfoForKey:TY_TOKEN]];
    [MBProgressHUDManager showHUD];

    /// 用来控制数据为空时，显示空试图
    [WDGlobal shareInstance].emptyType = TYEmptyData;
    [[AFNetworkClient sharedClient] POST:URLStr parameters:mutableParams headers:headers progress:^(NSProgress * _Nonnull uploadProgress) {
        //进度
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *responseStr = [TYGlobal ty_jsonStringforDic:responseObject];
        NSLog(@"服务器response success=====url ===== %@，%@,%@",URLStr,mutableParams, responseStr);
        [MBProgressHUDManager hideHUD];
        
        if([WDGlobal shareInstance].isNeedSarch) {
            [WDGlobal shareInstance].emptyType = TYEmptySearch;

        }

//        NSDictionary *responseObject = [TYGlobal dictionaryWithJsonString:responseStr];
        if (responseObject && [responseObject isKindOfClass:[NSDictionary class]]) {
            // 开始验签
            NSDictionary *dict = [NSDictionary nullDic:responseObject];
            NSInteger code = 0;
            if(dict[@"code"]){
                code = [dict[@"code"] integerValue];
            } else {
                code = [dict[@"msgCode"] integerValue];
            }
                
//            NSInteger code = [dict[@"code"] integerValue];
            if (code == 200) {
                successBlock(YES, dict?:@{}, dict[@"msg"]);
            }else if (code == 401) {
                dispatch_async(dispatch_get_main_queue(), ^{
//                    [TYGlobal removeAllInfo];
//                    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//                    [delegate rootLoginVC];
                    [TYGlobal logout];
                });
                
            }else {
                successBlock(NO,nil,responseObject[@"msg"]);
                [MBProgressHUD promptDetailMessage:responseObject[@"msg"]?:@"" inView:nil];

            }
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error ======= %@",error);
        [MBProgressHUDManager hideHUD];

        NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
                     
        if(data) {
            NSDictionary * errorDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSDictionary *dict = [NSDictionary nullDic:errorDic];
            NSInteger code = [dict[@"code"] integerValue];
            
            if (code == 401) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [TYGlobal logout];
//                    [TYGlobal removeAllInfo];
//                    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//                    [delegate rootLoginVC];
                    [MBProgressHUD promptMessage:dict[@"msg"]?:@"" inView:nil];
                });
                
            }
        }
        
        [WDGlobal shareInstance].emptyType = TYEmptyNetworkError;
        
        failureBlock(error.localizedDescription);
        
    }];
    
}

/**
 *  get请求
 *
 *  @param url          链接
 *  @param parameters   参数
 *  @param successBlock 成功block
 *  @param failureBlock 失败block
 */
+ (void)getRequest:(NSString*)url parameters:(NSDictionary *)parameters successBlock:(void (^)(BOOL success,NSDictionary *data,NSString* msg))successBlock failureBlock:(void (^)(NSString* description))failureBlock
{
    NSString *URLStr = [NSString stringWithFormat:@"%@%@",URL_main,url];
    
    NSString *token = [USER_DEFAULTS objectForKey:@"token"];
    NSMutableDictionary *headers = @{}.mutableCopy;
    headers[@"token"] = token;
    headers[@"Authorization"] = [NSString stringWithFormat:@"Bearer %@",[WDUtil getInfoForKey:TY_TOKEN]];
    [MBProgressHUDManager showHUD];

    [[AFNetworkClient sharedClient] GET:URLStr parameters:parameters headers:headers progress:^(NSProgress * _Nonnull downloadProgress) {
        //进度
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *responseStr = [TYGlobal ty_jsonStringforDic:responseObject];
        NSLog(@"服务器response success=====url ===== %@,%@",URLStr, responseStr);
        [MBProgressHUDManager hideHUD];

        if (responseObject && [responseObject isKindOfClass:[NSDictionary class]]) {
            // 开始验签
            NSDictionary *dict = [NSDictionary nullDic:responseObject];
            NSInteger code = 0;
            if(dict[@"code"]){
                code = [dict[@"code"] integerValue];
            } else {
                code = [dict[@"msgCode"] integerValue];
            }
            
            if (code == 200) {
                successBlock(YES, dict, dict[@"msg"]?:dict[@"msgDesc"]);
            }else if (code == 401) {
                dispatch_async(dispatch_get_main_queue(), ^{
//                    [TYGlobal removeAllInfo];
//                    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//                    [delegate rootLoginVC];
                    [TYGlobal logout];
                });
                
            }else {
                successBlock(NO,nil,responseObject[@"msg"]);
                [MBProgressHUD promptMessage:responseObject[@"msg"]?:@"" inView:nil];
            }
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUDManager hideHUD];

//        failureBlock(error.localizedDescription);
        NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
                 
        if(data ) {
            NSDictionary * errorDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSDictionary *dict = [NSDictionary nullDic:errorDic];
            NSInteger code = [dict[@"code"] integerValue];
            
            if (code == 401) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
//                    [TYGlobal removeAllInfo];
//                    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//                    [delegate rootLoginVC];
                    [TYGlobal logout];
                    [MBProgressHUD promptMessage:dict[@"msg"]?:@"" inView:nil];
                });
                
            }
        }
        
        failureBlock(error.localizedDescription);

        
    }];
    
}

+ (void)uploadFileWithOption:(NSDictionary *)paramDic
              withRequestURL:(NSString*)requestURL
                   dataArray:(NSMutableArray *)dataArray
                    dataName:(NSMutableArray *)dataName
                     dataKey:(NSMutableArray *)dataKey
             downloadSuccess:(void (^)(id responseObject))success
             downloadFailure:(void (^)(NSError *error))failure
                    progress:(void (^)(float progress))progress

{

    
    
    //1。创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];


    NSMutableDictionary *mulParameters = [NSMutableDictionary dictionaryWithDictionary:paramDic];
    NSString *URLStr = [NSString stringWithFormat:@"%@%@",URL_main,requestURL];
    
    NSString *token = [USER_DEFAULTS objectForKey:@"token"];
    NSMutableDictionary *headers = @{}.mutableCopy;
    headers[@"token"] = token;
    headers[@"Authorization"] = [NSString stringWithFormat:@"Bearer %@",[WDUtil getInfoForKey:TY_TOKEN]];
    [MBProgressHUDManager showHUD];
    

    
    [[AFNetworkClient sharedClient] POST:URLStr parameters:nil headers:headers constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //上传文件参数
        
        if (dataArray.count > 0) {
            
            [dataArray enumerateObjectsUsingBlock:^(UIImage *image, NSUInteger idx, BOOL * _Nonnull stop) {
                
                NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
                formatter.dateFormat=@"yyyyMMddHHmmss";
                NSString *str=[formatter stringFromDate:[NSDate date]];
                NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
                NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
                
                [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
                
            }];
            
            
        }
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        progress(1.0*uploadProgress.completedUnitCount/uploadProgress.totalUnitCount);
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *weatherDic = responseObject;
        NSLog(@"%@",responseObject);
        if ([[weatherDic objectForKey:@"code"] integerValue] == 200) {
            
            //请求成功
            success(weatherDic);
            
        }else{
            
            NSError *error = nil;
            
            failure(error);
            //            [ZJPublicClass textBouncedWithMessage:[weatherDic objectForKey:@"msg"]];
        }
        
        [MBProgressHUDManager hideHUD];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //请求失败
        failure(error);
        [MBProgressHUDManager hideHUD];

        
    }];
    
}

+ (void)downloadFileWithOption:(NSDictionary *)paramDic
                 withInferface:(NSString*)requestURL
                     savedPath:(NSString*)savedPath
               downloadSuccess:(void (^)(id responseObject))success
               downloadFailure:(void (^)(NSError *error))failure
                      progress:(void (^)(float progress))progress

{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    requestURL = [requestURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];;
    
    savedPath = [NSString stringWithFormat:@"file://%@",[NSHomeDirectory() stringByAppendingString:@"/Documents/music"]];
    
    //2.确定请求的URL地址
    NSURL *url = [NSURL URLWithString:requestURL];
    
    //3.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //下载任务
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        //加载进度
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //下载存放地址，要返回存放地址(存放地址前面加file://)
        
        return [NSURL URLWithString:savedPath];
        
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        success(response);
        // 下载完成之后，解压缩文件
        
    }];
    [task resume];
    
}


@end
